import { Component,ChangeDetectorRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RegisterpwdPage } from '../registerpwd/registerpwd';
import { StorageProvider } from '../../providers/storage/storage';
import { HttpserviesProvider } from '../../providers/httpservies/httpservies';

/**
 * Generated class for the RegistersignPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-registersign',
  templateUrl: 'registersign.html',
})
export class RegistersignPage {

  public tel = '';  //电话号码
  public code = ''; //验证码
  //是否显示重新发送按钮，默认显示倒计时按钮， 倒计时到0的时候显示重新发送按钮
  public isShowSend = false   
  public timeNum = 8;

  constructor(public navCtrl: NavController, public navParams: NavParams,public storage:StorageProvider,public httpServe:HttpserviesProvider) {

    //获取当前输入的电话号码
    this.tel = this.storage.get('register_tel');
    //加载完视图，调用发送验证码的请求
    this.doTimerNum();

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegistersignPage');
  }

  //倒计时
  doTimerNum(){
    var timer = setInterval(()=>{
      --this.timeNum;
      console.log(this.timeNum);
      if(this.timeNum == 0){
        //清除定时器
        clearInterval(timer);
        this.isShowSend = true;
      }
    },1000)
  }

  //重新发送验证码
  anewSendCode(){
    var url = 'api/sendCode';
      this.httpServe.doPostData(url,{"tel":this.tel},(data)=>{
        console.log(data);
        if(data.success){//获取到验证码成功
          this.timeNum = 8;
          this.doTimerNum();
          this.isShowSend = false;
        }else{
          alert('获取验证码失败，请稍后重试');
        }
      })
  }

  //跳转到下个页面
  goRegisterPwd(){
    //验证是否输入验证码
    if(!this.code.length){
      alert('请输入验证码');
      return;
    }

    //验证验证码是否输入正确
    var api = 'api/validateCode';
    this.httpServe.doPostData(api,{'tel':this.tel,'code':this.code},(data)=>{
      console.log(data);
      if(data.success){
        this.storage.set('code',this.code); //保存验证码
        this.navCtrl.push(RegisterpwdPage);
      }else{
        alert('验证码不正确');
      }
    })
  }

}
